package com.jd.sunny.java;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description:java proxy offerd by oracle
 * @author:sunlin
 * @since:2012-12-04 16:58
 * @version:1.0.0
 */
public class TestProxy {

    public static void main(String[]args){
        Drive drive = new DriveImpl();
        // use Proxy class to create proxy which omit us to create proxy class extends the interface
        Drive proxy =(Drive) Proxy.newProxyInstance(drive.getClass().getClassLoader(),drive.getClass().getInterfaces(), new MyInvocationHandle(drive));
        proxy.drive();
    }
}


/**
 * implement InvocationHandler
 */
class MyInvocationHandle implements InvocationHandler{
    private Object object = null;

    MyInvocationHandle(Object object) {
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName() + " invoke start");
        Object result =  method.invoke(object,args);
        return result;
    }

}

interface Drive{
    public void drive();
}

class DriveImpl implements Drive {
    public void drive() {
        System.out.println("sunlin is driving");
    }
}

